//
//  MoreVersionsVC.m
//  PgyHelper
//
//  Created by 鹏鹏 on 2021/1/6.
//  Copyright © 2021 CleverPeng. All rights reserved.
//

#import "MoreVersionsVC.h"
#import "RequestTool.h"
#import "MoreBuildsTCell.h"
#import "PPTools.h"
#import "NSArray+Ex.h"
#import "CustomAsyncOperation.h"

@interface MoreVersionsVC () <UITableViewDelegate, UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray <MoreBuildsModel *> *otherAppModels;

@property (nonatomic, assign) NSInteger page;

@property (nonatomic, assign) BOOL isEditing;
/// 每次编辑模式弹出一次即可
@property (nonatomic, assign) BOOL hasShowSelectAll;
@property (nonatomic, strong) NSOperationQueue *deleteQueue;

@end

@implementation MoreVersionsVC

- (NSOperationQueue *)deleteQueue {
    if (nil == _deleteQueue) {
        _deleteQueue = [[NSOperationQueue alloc] init];
        _deleteQueue.maxConcurrentOperationCount = 4;
        [_deleteQueue addObserver:self forKeyPath:@"operationCount" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _deleteQueue;
}

- (void)setIsEditing:(BOOL)isEditing {
    _isEditing = isEditing;

    if (isEditing) {
        self.hasShowSelectAll = NO;
    }

    for (MoreBuildsModel *model in self.otherAppModels) {
        model.isSelected = NO;
    }
}

- (instancetype)init {
    if (self = [super init]) {
        self.page = 1;
    }
    return self;
}

- (NSMutableArray<MoreBuildsModel *> *)otherAppModels {
    if (nil == _otherAppModels) {
        _otherAppModels = [NSMutableArray array];
    }
    return _otherAppModels;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    [self loadMainView];
}

- (void)loadMainView {

    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MoreBuildsTCell class]) bundle:nil] forCellReuseIdentifier:cellIdentifier];
    self.tableView.tableFooterView = [UIView new];

    MJWeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadDataList:weakSelf.page];
    }];
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf loadDataList:weakSelf.page + 1];
    }];

    [self.tableView.mj_header beginRefreshing];
}

#pragma mark - request

- (IBAction)refreshDataList:(id)sender {
    self.isEditing = NO;
    [self.tableView reloadData];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadDataList:(NSInteger)page {
    NSString *params = [NSString stringWithFormat:@"_api_key=%@&appKey=%@&page=%ld", [RequestTool get_api_key], self.appModel.appKey, page];
    WEAKSELF
    [RequestTool postWith:HOST_URL_app_builds paramsString:params completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        if (!isSuccess) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:message afterDelay:1.5];
            return;
        }

        if (nil == responseDataDic) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:@"数据异常" afterDelay:1.5];
            return;
        }

        NSArray *list = responseDataDic[@"list"];
        if (list.count > 0) {
            weakSelf.page = page;
        }
        if (page == 1) {
            [weakSelf.otherAppModels removeAllObjects];
        }

        NSArray *models = [NSArray yy_modelArrayWithClass:[MoreBuildsModel class] json:list];
        [weakSelf.otherAppModels addObjectsFromArray:models];
        [weakSelf.tableView reloadData];
    }];
}

- (void)requestDeleteVersionAtIndex:(NSIndexPath *)indexPath {
    MoreBuildsModel *buildModel = self.otherAppModels[indexPath.section];
    NSString *params = [NSString stringWithFormat:@"_api_key=%@&buildKey=%@", [RequestTool get_api_key], buildModel.buildKey];
    WEAKSELF
    [RequestTool postWith:HOST_URL_app_buildDelete paramsString:params completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        if (!isSuccess) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:message afterDelay:1.5];
            return;
        }

        if (nil == responseDataDic) {
            [MBProgressHUD showInfoOnView:weakSelf.view WithStatus:@"数据异常" afterDelay:1.5];
            return;
        }

        [weakSelf.otherAppModels removeObjectAtIndex:indexPath.section];
        [weakSelf.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationLeft];
        
        [weakSelf.tableView reloadData];
    }];
}

- (void)requestDeleteVersionWithBuildModel:(MoreBuildsModel *)buildModel completeHandler:(void(^)(BOOL isSuccess))completeHandler {
    NSString *params = [NSString stringWithFormat:@"_api_key=%@&buildKey=%@", [RequestTool get_api_key], buildModel.buildKey];
    WEAKSELF
    [RequestTool postWith:HOST_URL_app_buildDelete paramsString:params completeHandler:^(NSString * _Nullable responseString, NSDictionary * _Nullable responseDataDic, BOOL isSuccess, NSString * _Nullable message) {

        if (nil == completeHandler) {
            return;
        }
        if (!isSuccess) {
            completeHandler(NO);
            return;
        }

        if (nil == responseDataDic) {
            completeHandler(NO);
            return;
        }

        completeHandler(YES);
    }];
}

- (IBAction)doChangeEditStatusAction:(UIBarButtonItem *)sender {

    if (self.isEditing) {
        if (self.hasShowSelectAll) {
            [self doCompleteDeleteAlert];
        } else {
            [self doSelectAllAlert];
            self.hasShowSelectAll = YES;
        }
    } else {
        self.isEditing = !self.isEditing;
        [self.tableView reloadData];
    }
}

- (void)doCompleteDeleteAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否删除并返回" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定删除" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self doDeleteSelectedVersionsAction];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消并返回" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        self.isEditing = !self.isEditing;
        [self.tableView reloadData];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)doSelectAllAlert {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"是否需要全选" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定全选" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        for (MoreBuildsModel *model in self.otherAppModels) {
            model.isSelected = YES;
        }
        [self.tableView reloadData];
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"不全选并继续" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        [self doCompleteDeleteAlert];
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)doDeleteSelectedVersionsAction {
    
    __weak typeof(self) weakSelf = self;
    [[self.otherAppModels filter:^BOOL(MoreBuildsModel * _Nonnull element) {
        return element.isSelected;
    }] enumeration:^(MoreBuildsModel * _Nonnull element, NSInteger index, NSInteger totalCount) {

        CustomAsyncOperation *operation = [[CustomAsyncOperation alloc] init];

        operation.mainOperationDoBlock = ^BOOL(CustomAsyncOperation * _Nonnull operation) {

            [weakSelf requestDeleteVersionWithBuildModel:element completeHandler:^(BOOL isSuccess) {
                [operation finishOperation];
            }];

            return NO;
        };
        [weakSelf.deleteQueue addOperation:operation];
    }];
}

#pragma mark - notification

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    if ([keyPath isEqualToString:@"operationCount"]) {
        if (self.deleteQueue.operationCount == 0) {
            self.isEditing = NO;
            [self.tableView reloadData];
            [self.tableView.mj_header beginRefreshing];
        }
    }
}

#pragma mark UITableView delegate, dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.otherAppModels.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

static NSString *cellIdentifier = @"MoreBuildsTCell";
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MoreBuildsTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (nil == cell) {
        cell = [[MoreBuildsTCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.isEditingStatus = self.isEditing;
    cell.buildsModel = self.otherAppModels[indexPath.section];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    if (self.isEditing) {
        self.otherAppModels[indexPath.section].isSelected = !self.otherAppModels[indexPath.section].isSelected;
        [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    } else {
        MoreBuildsModel *buildsModel = self.otherAppModels[indexPath.section];
        [PPTools jumpToInstallDirectly:buildsModel.buildKey buildPassword:self.appModel.buildKey];
    }
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForFooterInSection:(NSInteger)section {
    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return  UITableViewAutomaticDimension;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 100;
}

- (UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    WEAKSELF
    UIContextualAction *action = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleNormal title:@"删除" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {

        [weakSelf requestDeleteVersionAtIndex:indexPath];

        completionHandler(YES);
    }];
    action.backgroundColor = [UIColor redColor];
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[action]];
    return config;

}

@end
